package yzbx.personalwebsite.service.impl;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import yzbx.personalwebsite.entity.HotTodayEntity;
import yzbx.personalwebsite.service.GetHotTodayService;
import yzbx.personalwebsite.tool.Httptool;
import yzbx.personalwebsite.tool.RedisTool;

import java.util.ArrayList;
import java.util.List;

/**
 * {@code @Author} zxm
 * {@code @Description} 获取百度热点数据服务类
 * {@code @Date} 2024/09/29/11:27
 * {@code @Version} 1.0
 */
@Service
public class GetHotTodayServiceBaidu extends GetHotTodayService {

    private static final Logger LOGGER = LoggerFactory.getLogger(GetHotTodayServiceBaidu.class);

    public GetHotTodayServiceBaidu(RedisTool redisTool, Httptool httptool) {
        super(redisTool, httptool);
    }

    public List<HotTodayEntity> GetData(String logTheme) {
        List<HotTodayEntity> hotTodayList = new ArrayList<>();
        String url = "https://top.baidu.com/board?tab=realtime";
        try {
            Document doc = Jsoup.connect(url).get();
            // 标题
            Elements titles = doc.select(".c-single-text-ellipsis");
            // 链接
            Elements urls = doc.select(".category-wrap_iQLoo a.img-wrapper_29V76");
            for (int i = 0; i < titles.size() && hotTodayList.size() < DATA_NUM_MAX; i++) {
                HotTodayEntity hotToday = new HotTodayEntity();
                hotToday.setIndex(i + 1 + "");
                hotToday.setTitle(titles.get(i).text().trim());
                hotToday.setUrl(urls.get(i).attr("href"));
                hotTodayList.add(hotToday);
            }
            LOGGER.info("抓取{}数据成功，{}条", logTheme, hotTodayList.size());
        } catch (Exception e) {
            LOGGER.warn("抓取{}数据失败，失败信息：{}", logTheme, e.getMessage());
        }
        return hotTodayList;
    }
}
